﻿/*
 *  Source code courtesy of the desktopWeb.CodePlex.com community project. See MS-PL license on Codeplex.com. 
 *  This is beta code not intended for a production application.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Data.SqlClient;
using System.ComponentModel;
using System.Data;

namespace MyData.Activities.SQLAzure
{
  [Designer(typeof(MyData.Activities.Designers.SelectDataTableDesigner))]
  public sealed class SelectDataTableActivity : CodeActivity
  {
    [RequiredArgument]
    public InArgument<SqlConnectionStringBuilder> SqlConnectionBuilder { get; set; }
    [RequiredArgument]
    public InArgument<string> SqlViewName { get; set; }
    [RequiredArgument]
    public InArgument<List<string>> ColumnNames { get; set; }

    //The InitialCatalog comes from the connection SqlConnectionBuilder
    [RequiredArgument]
    public InArgument<string> InitialCatalog { get; set; }

    public OutArgument<DataTable> DataTable { get; set; }

    protected override void Execute(CodeActivityContext context)
    {
      string viewName = SqlViewName.Get(context);
      List<string> columnNameList = ColumnNames.Get(context);

      using (SqlConnection connection = new SqlConnection(SqlConnectionBuilder.Get(context).ToString()))
      {
        using (SqlCommand command = connection.CreateCommand())
        {
          connection.Open();

          string columnNames = string.Empty;
          foreach (string columnName in columnNameList)
          {
            columnNames += columnName + " ,";
          }

          if (columnNames.Length > 0)
            columnNames = columnNames.Substring(0, columnNames.Length - 1);

          command.CommandText = String.Format("SELECT {0} FROM {1}", columnNames, viewName);

          DataTable dt = new DataTable();
          SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
          dataAdapter.Fill(dt);

          DataTable.Set(context, dt);
        }
      }
    }
  }
}




